package ynu.edu.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.mapper.CartMapper;
import ynu.edu.mapper.OrderDetailetMapper;
import ynu.edu.mapper.OrdersMapper;
import ynu.edu.po.Cart;
import ynu.edu.po.OrderDetailet;
import ynu.edu.po.Orders;
import ynu.edu.service.OrdersService;
import ynu.edu.util.CommonUtil;


import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailetMapper orderDetailetMapper;

    @Override
    @Transactional
    public int createOrders(String userId,Integer businessId,Integer daId,Double orderTotal) {
//1、查询当前用户购物车中当前商家的所有食品
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setBusinessId(businessId);
        List<Cart> cartList = cartMapper.listCart(cart);

//2、创建订单（返回生成的订单编号）
        Orders orders = new Orders();
        orders.setUserId(userId);
        orders.setBusinessId(businessId);
        orders.setDaId(daId);
        orders.setOrderTotal(orderTotal);
        orders.setOrderDate(CommonUtil.getCurrentDate());
        ordersMapper.saveOrders(orders);
        int orderId = orders.getOrderId();
//3、批量添加订单明细
        List<OrderDetailet> list = new ArrayList<>();
        for(Cart c : cartList) {
            OrderDetailet od = new OrderDetailet();
            od.setOrderId(orderId);
            od.setFoodId(c.getFoodId());
            od.setQuantity(c.getQuantity());
            list.add(od);
        }
        orderDetailetMapper.saveOrderDetailetBatch(list);
//4、从购物车表中删除相关食品信息
        cartMapper.removeCart(cart);
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        Orders orders = new Orders();
        orders = ordersMapper.getOrdersById(orderId);
        List<OrderDetailet> list = orderDetailetMapper.listOrderDetailetByOrderId(orderId);
        orders.setList(list);
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId){
        List<Orders> list = new ArrayList<>();
        list = ordersMapper.listOrdersByUserId(userId);
        for(Orders o: list){
            List<OrderDetailet> odList = orderDetailetMapper.listOrderDetailetByOrderId(o.getOrderId());
            o.setList(odList);
        }
        return list;
    }

    @Override
    public int updateOrdersState(Integer orderId, Integer orderState) {
        return ordersMapper.updateOrdersState(orderId, orderState);
    }

}
